import { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Box,
  CircularProgress,
  Alert,
} from '@mui/material';
import { ResourceService } from '../services/ResourceService';
import { useAuth } from '../../auth/AuthContext';

interface SaveResourceProps {
  open: boolean;
  onClose: () => void;
  onSaveSuccess?: () => void;
}

const SaveResource = ({ open, onClose, onSaveSuccess }: SaveResourceProps) => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [coverUrl, setCoverUrl] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const { user } = useAuth();

  const handleSubmit = async () => {
    if (!user) return;

    if (!title.trim()) {
      setError('请输入资源标题');
      return;
    }

    try {
      setSaving(true);
      setError(null);

      await ResourceService.saveResource({
        title: title.trim(),
        description: description.trim(),
        coverUrl: coverUrl.trim(),
        uploaderId: user.id,
        uploaderName: user.username,
      });

      onSaveSuccess?.();
      handleClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存资源失败');
    } finally {
      setSaving(false);
    }
  };

  const handleClose = () => {
    setTitle('');
    setDescription('');
    setCoverUrl('');
    setError(null);
    onClose();
  };

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
      <DialogTitle>保存资源</DialogTitle>
      <DialogContent>
        <Box sx={{ pt: 2 }}>
          {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {error}
            </Alert>
          )}
          <TextField
            fullWidth
            label="资源标题"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
            disabled={saving}
            sx={{ mb: 2 }}
          />
          <TextField
            fullWidth
            label="资源描述"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            multiline
            rows={4}
            disabled={saving}
            sx={{ mb: 2 }}
          />
          <TextField
            fullWidth
            label="封面图片URL"
            value={coverUrl}
            onChange={(e) => setCoverUrl(e.target.value)}
            placeholder="https://example.com/image.jpg"
            disabled={saving}
          />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} disabled={saving}>
          取消
        </Button>
        <Button
          onClick={handleSubmit}
          disabled={!title.trim() || saving}
          variant="contained"
          startIcon={saving ? <CircularProgress size={20} /> : undefined}
        >
          {saving ? '保存中...' : '保存'}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default SaveResource;